package kGeom;

public class kTri extends kElement {
	
	public kVec p0;
	public kVec p1;
	public kVec p2;
	
	public kTri(kVec pt0, kVec pt1, kVec pt2){
		p0 = pt0;
		p1 = pt1;
		p2 = pt2;
	}
	
	public kTri(float x0,float y0,float z0,float x1,float y1,float z1,float x2,float y2,float z2 ){
		p0 = new kVec(x0,y0,z0);
		p1 = new kVec(x1,y1,z1);
		p2 = new kVec(x2,y2,z2);
	}	
	
	
	public kVec centroid(){
		return kVec.centroid(new kVec[]{p0,p1,p2});
	}
	
	public float distanceToCentroid(kVec p){
		return centroid().distance(p);
	}
	
	
	public kVec closestPoint(kVec v){
		kVec normal = kVec.cross(new kVec(p0,p1), new kVec(p0,p2));
		normal.normalize();
		normal.resize(new kVec(p0,v).dot(normal));
		normal.invert();
		kVec vp = kVec.translate(v, normal); // the point on the plane of the triangle
		
		kVec x0 = kVec.cross(new kVec(p0,vp), new kVec(p0,p1));	
		kVec x1 = kVec.cross(new kVec(p1,vp), new kVec(p1,p2));
		kVec x2 = kVec.cross(new kVec(p2,vp), new kVec(p2,p0));
		if ((x0.isCoincident(x1)) && (x1.isCoincident(x2))) {
			// point is inside triangle
			return vp;
		} else {
			// point is outside triangle
			kLine ln0 = new kLine(p0,p1); kVec ret = ln0.closestPoint(vp);
			kLine ln1 = new kLine(p1,p2);kVec pj1 = ln1.closestPoint(vp);
			kLine ln2 = new kLine(p2,p0);kVec pj2 = ln2.closestPoint(vp);
			
			if ( pj1.distance(v) < ret.distance(v) ) ret = pj1;
			if ( pj2.distance(v) < ret.distance(v) ) ret = pj2;
			return ret;
		}
	}
	
	
	
}
